<template>
    <div class="page-orderDetail" v-if="orderInfoList.length > 0">
        <!-- 当前订单状态 -->
        <div class="orderSate">
            <!-- 状态:等待付款 -->
            <div class="orderState-content" v-if="orderInfoList[0].orderState === '未支付'">
                <div class="content-title">
                    <van-icon class="title-icon" name="arrow-left" color="#fff" @click="back_btn"/>
                    <div class="title-content">
                        <SvgIcon class="content-icon" name="wait" width="22px" height="22px" color="#fff"></SvgIcon>
                        <span class="content-text">等待付款</span>
                    </div>
                </div>
                <div class="content-center">
                    <div class="center-text">
                        <span class="text-item">应付金额:￥{{ productTotalPrice + productTotalDeliverFee }}</span>&nbsp;&nbsp;
                        <span class="text-item" v-if="restTime !== null">支付剩余 {{ restTime }}</span>
                        <span class="text-item" v-else>订单已超时取消</span>
                    </div>
                </div>
                <div class="content-btn" v-if="restTime !== null">
                    <span class="btn-text" @click="goPay_btn">去支付</span>
                </div>
            </div>
            <!-- 状态:待发货 -->
            <div class="orderState-content" v-if="orderInfoList[0].orderState === '待发货' || orderInfoList[0].orderState === '已支付'">
                <div class="content-title">
                    <van-icon class="title-icon" name="arrow-left" color="#fff" @click="back_btn"/>
                    <div class="title-content">
                        <SvgIcon class="content-icon" name="deliverGoods" width="22px" height="22px" color="#fff"></SvgIcon>
                        <span class="content-text">等待发货</span>
                    </div>
                </div>
                <div class="content-center">
                    <div class="center-text">
                        <span class="text-item">已支付金额:￥{{ productTotalPrice + productTotalDeliverFee }}</span>&nbsp;&nbsp;
                    </div>
                </div>
                <div class="content-btn">
                    <span class="btn-text" @click="connect_service">联系客服</span>
                </div>
            </div>
            <!-- 状态:运输中 -->
            <div class="orderState-content" v-if="orderInfoList[0].orderState === '运输中'">
                <div class="content-title">
                    <van-icon class="title-icon" name="arrow-left" color="#fff" @click="back_btn"/>
                    <div class="title-content">
                        <SvgIcon class="content-icon" name="inTransit" width="22px" height="22px" color="#fff"></SvgIcon>
                        <span class="content-text">包裹运输中</span>
                    </div>
                </div>
                <div class="content-center">
                    <div class="center-text">
                        <span class="text-item">物流信息:{{ orderInfoList[0].logisticsInfo }}</span>&nbsp;&nbsp;
                    </div>
                </div>
                <div class="content-btn">
                    <span class="btn-text" @click="cancelOrder_btn">取消订单</span>
                </div>
            </div>
            <!-- 状态:已收货-->
            <div class="orderState-content" v-if="orderInfoList[0].orderState === '已收货'">
                <div class="content-title">
                    <van-icon class="title-icon" name="arrow-left" color="#fff" @click="back_btn"/>
                    <div class="title-content">
                        <SvgIcon class="content-icon" name="haveBeenSigned" width="22px" height="22px" color="#fff"></SvgIcon>
                        <span class="content-text">包裹已签收</span>
                    </div>
                </div>
                <div class="content-center">
                    <div class="center-text">
                        <span class="text-item">您的快递已放置在菜鸟驿站,请尽快取件哦!</span>&nbsp;&nbsp;
                    </div>
                </div>
                <div class="content-btn">
                    <span class="btn-text" @click="evaluate_btn">去评价</span>
                </div>
            </div>
            <!-- 状态:已退货 -->
            <div class="orderState-content" v-if="orderInfoList[0].orderState === '已退货'">
                <div class="content-title">
                    <van-icon class="title-icon" name="arrow-left" color="#fff" @click="back_btn"/>
                    <div class="title-content">
                        <SvgIcon class="content-icon" name="salesReturn" width="32px" height="32px" color="#fff"></SvgIcon>
                        <span class="content-text">包裹退回中</span>
                    </div>
                </div>
                <div class="content-center">
                    <div class="center-text">
                        <span class="text-item">退货物流信息:{{ orderInfoList[0].logisticsInfo }}</span>&nbsp;&nbsp;
                    </div>
                </div>
                <div class="content-btn">
                    <span class="btn-text" @click="connect_service">联系客服</span>
                </div>
            </div>
            <!-- 状态:订单已取消 -->
            <div class="orderState-content" v-if="orderInfoList[0].orderState === '已取消'">
                <div class="content-title">
                    <van-icon class="title-icon" name="arrow-left" color="#fff" @click="back_btn"/>
                    <div class="title-content">
                        <SvgIcon class="content-icon" name="orderCancel" width="28px" height="28px" color="#fff"></SvgIcon>
                        <span class="content-text">订单已取消</span>
                    </div>
                </div>
                <div class="content-center">
                    <div class="center-text">
                        <span class="text-item">订单已取消</span>
                    </div>
                </div>
                <div class="content-btn" v-if="restTime !== null">
                    <span class="btn-text" @click="delete_btn">删除订单</span>
                </div>
            </div>
        </div>
        <!-- 订单收货地址信息 -->
        <div class="address" v-if="false">
            <van-icon name="location-o" color="#9195a3" size="20"/>
            <div class="address-info">
                <span class="info-item info-user">{{ orderInfoList[0].linkUser + " " + orderInfoList[0].linkPhone }}</span>
                <span class="info-item info-address">{{ orderInfoList[0].linkAddress }}</span>
            </div>
        </div>
        <!-- 订单商品信息 -->
        <div class="product">
            <div class="product-item" v-for="item,index in orderInfoList" :key="index">
                <img class="item-img" :src="item.productInfo.commodityImgs.split(',')[0]" alt="">
                <div class="item-info">
                    <div class="info-productName">{{ item.productInfo.commodityName }}</div>
                    <div class="info-productAttr">
                        <span class="productAttr-item">{{ item.productStandardInfo.commodityAttr }}</span>
                    </div>
                    <div class="info-productPrice">
                        <span class="price-item">￥{{ item.productStandardInfo.commodityPrice }}</span>
                        <span class="number-item">{{ 'x' + item.commodityCount }}</span>
                    </div>
                </div>
            </div>
        </div>
        <!-- 订单总价信息 -->
        <div class="price">
            <div class="price-item price-product-total">
                <span class="total-tip">商品总价:</span>
                <span class="total-num">￥{{ productTotalPrice.toFixed(2) }}</span>
            </div>
            <div class="price-item price-deliver">
                <span class="deliver-tip">运费:</span>
                <span class="deliver-num">￥{{ productTotalDeliverFee.toFixed(2) }}</span>
            </div>
            <div class="price-item price-pay">
                <span class="pay-tip">订单金额:</span>
                <span class="pay-num">￥{{ (productTotalPrice + productTotalDeliverFee).toFixed(2) }}</span>
            </div>
        </div>
        <!-- 订单信息部分 -->
        <div class="info">
            <span class="info-title">订单信息</span>
            <div class="info-number">
                <span class="orderNumber">订单编号:{{ orderInfoList[0].orderId + (orderInfoList.length > 1 ? '+...' : '')}}</span>
                <span class="orderNumberCopy">复制</span>
            </div>
            <span class="info-time">下单时间:{{ orderInfoList[0].createTime }}</span>
        </div>
        <!-- 底部固定功能区 -->
        <div class="functional">
            <van-button v-if="orderInfoList[0].orderState === '未支付'" class="item-btn" type="primary" size="small" @click="goPay_btn">去支付</van-button>
            <van-button v-if="orderInfoList[0].orderState === '未支付' || orderInfoList[0].orderState === '已支付' || orderInfoList[0].orderState === '待发货' || orderInfoList[0].orderState === '运输中'" class="item-btn" type="default" size="small" @click="cancelOrder_btn">取消订单</van-button>
            <van-button class="item-btn" type="primary" plain size="small" @click="connect_service">联系客服</van-button>
            <van-button v-if="orderInfoList[0].orderState === '运输中'" class="item-btn" type="primary" size="small" @click="confirm_receipt_btn">确认收货</van-button>
            <van-button v-if="orderInfoList[0].orderState === '已收货'" class="item-btn" type="warning" size="small" @click="evaluate_btn">去评价</van-button>
            <van-button class="item-btn" type="danger" size="small" @click="delete_btn">删除订单</van-button>
        </div>
    </div>
</template>

<script setup lang="ts">
//引入vue
import { ref, onMounted, onBeforeUnmount } from "vue";
//引入vant4
import { Icon as VanIcon, Button as VanButton, showToast, showSuccessToast, showConfirmDialog, showLoadingToast } from "vant";
//引入vue-router
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
//@ts-ignore引入请求函数
import { reqProductOrderById, reqProductOrderByIds, reqUpdateProductOrder, reqDeleteProductOrder } from "@/api/order/index.ts";

//商品订单相关数据
let orderInfoList = ref([]);
let productTotalPrice = ref(0);
let productTotalDeliverFee = ref(0);
//支付剩余时间
let restTime = ref("00:10:00");

//获取订单详情信息
async function getOrderDetail () {
    //获取路由参数中的订单ids
    let orderIds:string[] = route.query.orderIds.split(",");
    if(orderIds.length === 0) return;
    let res = null;
    if(orderIds.length === 1) {
        res = await reqProductOrderById(orderIds[0]);
    } else if (orderIds.length > 1) {
        res = await reqProductOrderByIds(orderIds);
    }
    if(res.code === 200){
        orderInfoList.value = res?.result;
        //计算商品总价及总运费
        let temp1 = 0, temp2 = 0;
        res?.result.forEach(item => {
            temp1 += (item.commodityCount * item.productStandardInfo.commodityPrice);
            temp2 += item.orderTotalPrice;
        })
        productTotalPrice.value = Number(temp1.toFixed(2));
        productTotalDeliverFee.value = Number((temp2 - temp1).toFixed(2));
        //提示信息
        showToast("订单信息获取成功!");
        //判断当前订单状态为什么状态?待支付需要展示支付倒计时
        if(res?.result[0].orderState === "未支付"){
            restTimeFun();
        }
    }
    console.log("获取用户订单信息api",res);
}

//返回按钮事件
function back_btn () {
    //返回上一页(如果是从订单创建页 --> 订单详情 则不能返回上一页,应该返回上两页)
    if(router.options.history.state.back === '/create'){
        router.go(-2);  //返回上两页
    } else {
        router.go(-1);  //返回上一页
    }
}
//取消订单按钮
async function cancelOrder_btn () {
    let temp = orderInfoList.value.map(item => {
        return {
            orderId:item.orderId,
            orderState:"已取消"
        }
    })
    if(temp.length === 0) return showToast("出现未知错误!");
    //弹框提示
    showConfirmDialog({title: '提示',message:'确定取消订单吗?'})
    .then(async () => {
        // on confirm
        //发请求更新订单状态(此处若有多个订单需要更新,应当准备批量修改订单信息的接口,因为可能就此处会修改多个订单信息,就直接for调用接口了,懒得写了,哈哈)
        for(let i = 0; i < temp.length; i ++){
            let res = await reqUpdateProductOrder(temp[i]);
            if(res.code === 200){
                //无操作
            }
            console.log('修改订单信息api',res);
        }
        //提示信息
        showSuccessToast("订单取消成功!即将跳转到订单列表页...");
        //延时跳转
        setTimeout(()=>{
            router.push("/orderList");
        },1500)
    })
    .catch(() => {
        // on cancel
        showToast("操作取消!");
    });
}
//去支付按钮
function goPay_btn () {
    //准备query参数
    const orderIds = orderInfoList.value.map(item => {return item.orderId}).toString();
    const price = productTotalDeliverFee.value + productTotalPrice.value;
    //提示
    showLoadingToast("加载中...");
    //延迟跳转到支付页
    setTimeout(()=>{
        router.push({path:"/payment",query:{orderIds,price}});
    },800);
}
//确认收货按钮
function confirm_receipt_btn () {
    let temp = orderInfoList.value.map(item => {
        return {
            orderId:item.orderId,
            orderState:"已收货"
        }
    })
    if(temp.length === 0) return showToast("出现未知错误!");
    //弹框提示
    showConfirmDialog({title: '提示',message:'确定收到商品了吗?'})
    .then(async () => {
        // on confirm
        //发请求更新订单状态(此处若有多个订单需要更新,应当准备批量修改订单信息的接口,因为可能就此处会修改多个订单信息,就直接for调用接口了,懒得写了,哈哈)
        for(let i = 0; i < temp.length; i ++){
            let res = await reqUpdateProductOrder(temp[i]);
            if(res.code === 200){
                //无操作
                showSuccessToast("收货成功!");
                setTimeout(() => {
                    //刷新页面
                    router.go(0);
                },1000)
            }
            console.log('修改订单信息api',res);
        }
    })
    .catch(() => {
        // on cancel
        showToast("操作取消!");
    });
}
//去评价按钮
function evaluate_btn () {
    showToast("功能开发中,敬请期待...");
}
//删除订单按钮
function delete_btn () {
    let temp = orderInfoList.value.map(item => {
        return item.orderId;
    })
    if(temp.length === 0) return showToast("出现未知错误!");
    //弹框提示
    showConfirmDialog({title: '提示',message:'确定删除该订单吗?'})
    .then(async () => {
        // on confirm
        let res = await reqDeleteProductOrder(temp);
        if(res.code === 200){
            //无操作
            showSuccessToast("订单删除成功!");
            setTimeout(() => {
                //延时跳转到订单列表页
                router.push("/orderList");
            },1000)
        }
        console.log('批量删除订单api',res);
    })
    .catch(() => {
        // on cancel
        showToast("操作取消!");
    });
}
//联系客服
function connect_service () {
    showToast("功能开发中,敬请期待...");
}

//十分钟倒计时
let timer:any = null;
const restTimeFun = () => {
    if(timer !== null) clearInterval(timer);
    let timeArr = restTime.value.split(":");
    let hours = Number(timeArr[0]);
    let minutes = Number(timeArr[1]);
    let seconds = Number(timeArr[2]);
    timer = setInterval(async () => {
        if(seconds > 0){
            seconds -- ;
        } else if(seconds === 0){
            minutes --;
            seconds = 60;
            seconds --;
        }
        //赋值
        let result = addZero(hours) +":"+ addZero(minutes) +":"+ addZero(seconds);
        restTime.value = result;
        //判断倒计时结束
        if(hours === 0 && minutes === 0 && seconds === 0){
            //订单超时处理
            showToast("订单超时已取消!")
            //发请求修改订单状态
            for(let i = 0; i < orderInfoList.value.length; i ++){
                let res = await reqUpdateProductOrder({orderId:orderInfoList.value[i].orderId,orderState:'已取消'});
                console.log('修订用户订单信息api',res);
            }
            //将相应的按钮置为禁用的状态
            restTime.value = null;
            clearInterval(timer);
        }    
        //console.log(result);
    },1000)
}
//补零函数
function addZero (value:any) {
    if(value < 10) {
        return '0' + value;
    } else {
        return value;
    }
}
//orderIds=2024040806221712571734537932,2024040806221712571734538910
//vue生命周期
onMounted(() => {
    //获取订单详情
    getOrderDetail();
})
onBeforeUnmount(() => {
    clearInterval(timer);
})
</script>

<style lang="less" scoped>
.page-orderDetail{
    width: 375px;
    height: calc(100vh - 50px);
    background:#eff2f5;
    overflow: auto;
    /**当前订单状态 */
    .orderSate{
        width: 375px;
        height: 170px;
        padding: 20px;
        box-sizing: border-box;
        background: #b0d8ff;
        /**状态:等待付款 */
        .orderState-content{
            width: 100%;
            height: 100%;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: space-between;
            .content-title{
                width: 100%;
                display: flex;
                flex-direction: row;
                .title-content{
                    width: 290px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    .content-text{
                        font-size: 18px;
                        color: #fff;
                    }
                }
            }
            .content-center{
                width: 100%;
                display: flex;
                justify-content: center;
                .center-text{
                    font-size: 16px;
                    color: #fff;
                }
            }
            .content-btn{
                width: 130px;
                height: 35px;
                margin: 0 auto;
                text-align: center;
                line-height: 30px;
                border-radius: 20px;
                background: #fff;
                cursor: pointer;
                .btn-text{
                    font-size: 16px;
                    color: #9195a3;
                }
            }
        }
    }
    /**订单地址信息 */
    .address{
        width:360px;
        height:70px;
        margin:10px auto;
        padding:10px;
        box-sizing:border-box;
        background:#fff;
        border-radius:5px;
        display:flex;
        justify-content:space-between;
        align-items:center;
        .address-info{
            width:300px;
            display:flex;
            flex-direction:column;
            .info-item{
                font-size:12px;
                color:#9195a3;
                margin:3px 0;
            }
        }
    }
    /**订单商品信息 */
    .product{
        width: 360px;
        margin: 10px auto;
        border-radius: 5px;
        background: #fff;
        .product-item{
            width: 100%;
            height: 100px;
            padding: 9px;
            margin: 5px 0;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            .item-img{
                width: 80px;
                height: 80px;
                margin-right: 10px;
            }
            .item-info{
                width: 250px;
                height: 80px;
                display: flex;
                flex-direction: column;
                .info-productName{
                    flex: 2;
                    font-size: 16px;
                    color: #000;
                }
                .info-productAttr{
                    flex:1;
                    .productAttr-item{
                        font-size: 12px;
                        padding: 2px 4px;
                        color: #9195a3;
                        background: #f1f1f4;
                        border-radius: 3px;
                    }
                }
                .info-productPrice{
                    flex:1;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    .price-item{
                        font-size: 14px;
                        color: #f00;
                    }
                    .number-item{
                        font-size: 12px;
                        color: #000;
                    }
                }
            }
        }
    }
    /**订单配送时间、订单备注 */
    .price{
        width: 360px;
        margin: 10px auto;
        padding: 8px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        border-radius: 5px;
        background: #fff;
        .price-item{
            width: 100%;
            height: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 13px;
            .pay-num{
                font-size: 18px;
                color: #f00;
            }
        }
    }
    /**订单信息部分 */
    .info{
        width: 360px;
        margin: 10px auto;
        padding: 10px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        background: #fff;
        border-radius: 5px;
        .info-title{
            font-size: 16px;
            margin: 5px 0;
        }
        .info-number{
            display: flex;
            align-items: center;
            margin: 5px 0;
            .orderNumber{
                font-size: 14px;
                color: #000;
            }
            .orderNumberCopy{
                margin: 0 3px;
                font-size: 10px;
                padding: 2px;
                color: #9195a3;
                border: 1px solid #9195a3;
                border-radius: 5px;
                cursor: pointer;
            }
        }
        .info-time{
            font-size: 14px;
            color: #000;
        }
    }
    /**底部固定功能区 */
    .functional{
        width: 375px;
        height: 50px;
        background: #fff;
        padding: 3px 10px;
        box-sizing: border-box;
        position: fixed;
        bottom: 0;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .item-btn{
            margin: 0 5px;
        }
    }
}
</style>